package com.yang.crawler.strategy.schema;


import com.yang.crawler.strategy.IArticleCrawlStrategy;
import com.yang.crawler.strategy.annotations.ArticleCrawlStrategy;
import com.yang.crawler.strategy.enums.ArticleCrawlWebsiteEnum;
import com.yang.crawler.strategy.factory.ArticleCrawlStrategyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;

@Component
public class StrategyPostProcessor implements BeanPostProcessor {
    @Override
    public  Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (hasArticleCrawlStrategyAnno(bean)) {
            ArticleCrawlWebsiteEnum websiteEnum = bean.getClass().getAnnotation(ArticleCrawlStrategy.class).website();
            ArticleCrawlStrategyFactory.addArticleCrawlStrategy(websiteEnum.getWebsite(), (IArticleCrawlStrategy) bean);
        }
        return bean;
    }

    private boolean hasArticleCrawlStrategyAnno(Object bean) {
        return classHasAnnotation(bean, ArticleCrawlStrategy.class);
    }

    private boolean classHasAnnotation(Object bean, Class<? extends Annotation> annotationClazz) {
        return bean.getClass().isAnnotationPresent(annotationClazz);
    }

}

